<?php

namespace app\common\model;

use think\Exception;
use think\Model;

class Base extends Model implements BaseInterface
{
    /**
     * 添加数据
     * @param $data
     * @return false|int
     */
    public function data_add($data = [])
    {
        $this->save($data);
        return $this->getLastInsID();
    }

    /**
     * 更新
     * @param $condition
     * @param $data
     * @return false|int
     */
    public function data_update($condition, $data)
    {
        return $this->isUpdate(true)->save($data, $condition);
    }

    /**
     * 删除数据
     * @param $condition
     * @return false|int
     */
    public function data_del($condition)
    {
        return $this->where($condition)->delete();
    }

    /**
     * 查询一条数据
     * @param $condition
     * @param $field
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function data_get($condition, $field = '*')
    {
        $data = $this->where($condition)
            ->field($field)
            ->find();
        return $data ? $data->toArray() : [];
    }

    /**
     * 返回多条数据
     * @param $condition array 条件数组
     * @param $page int 当前分页
     * @param $field string|array 字段
     * @param $order string 排序，如 id desc
     * @param $pageSize int 分页大小
     * @return Base|array
     * @throws Exception
     */
    public function data_list($condition, $page = 1, $field = '*', $order = '', $pageSize = 10)
    {
        $data = $this->where($condition)
            ->limit(($page - 1) * $pageSize, $pageSize)
            ->field($field);
        if ($order) $data->order($order);
        $data = $data->select();
        return $data ? collection((array)$data)->toArray() : [];
    }

    /**
     * 获取统计
     * @param $condition
     * @param $field
     * @return int|string
     * @throws Exception
     */
    public function data_count($condition, $field = '*')
    {
        $data = $this->where($condition)->count($field);
        return $data ?: 0;
    }

}